<template>
  <view class="goodsdetail-container">
    <!-- 商品轮播图 -->
    <view class="card">
      <swiper class="my-swipe" :autoplay="3000" indicator-color="#ccc" :circular="true" :interval="3000"
        :indicator-dots="true">
        <swiper-item v-for="item in thumbImages" :key="item.src">
          <image :src="item.src" />
        </swiper-item>
      </swiper>
    </view>
    <!-- 商品名称 -->
    <view class="card">
      <view class="price">
        <span class="sellPrice">¥{{ goodsInfo.sell_price }}</span>
        <span class="shopPrice"><s>¥{{ goodsInfo.market_price }}</s></span>
      </view>
      <div class="goodsName multi-ellipsis--l2">{{ goodsInfo.title }}</div>
    </view>
    <!-- 商品介绍 -->
    <view class="card">
      <view content-position="left">介绍</view>
      <view class="content">
        <rich-text :nodes="formatContent" class="rich-content"></rich-text>
      </view>
    </view>
    <!-- 商品sku区域 -->
    <uni-popup ref="skuPopup" type="bottom">
      <view class="sku-popup">
        <view class="sku-header">
          <image :src="goodsInfo.thumb_path || thumbImages[0]?.src" mode="aspectFill" class="goods-thumb"></image>
          <view class="sku-info">
            <view class="price">¥{{ goodsInfo.sell_price }}</view>
            <view class="stock">库存：{{ goodsInfo.stock_quantity }}件</view>
            <view class="selected">已选：{{ buyNumber }}件</view>
          </view>
          <text class="close-btn" @click="closeSkuPopup">×</text>
        </view>

        <scroll-view scroll-y class="sku-content">
          <!-- 数量选择 -->
          <view class="sku-item">
            <text class="item-title">购买数量</text>
            <uni-number-box :min="1" :max="goodsInfo.stock_quantity" :value="buyNumber"
              @change="onNumberChange"></uni-number-box>
          </view>

          <!-- 其他信息 -->
          <view class="other-info">
            <text class="info-title">其他信息</text>
            <view class="info-item">商品货号：{{ goodsInfo.goods_no }}</view>
            <view class="info-item">库存情况：{{ goodsInfo.stock_quantity }}件</view>
            <view class="info-item">上架时间：{{ formattedAddTime }}</view>
          </view>
        </scroll-view>

        <view class="sku-footer">
          <button class="btn-cart" @click="handleAddCart" v-if="isSkuShowAddCart">加入购物车</button>
          <button class="btn-buy" @click="handleBuyNow">立即购买</button>
        </view>
      </view>
    </uni-popup>

    <!-- 底部操作栏 -->
    <view class="footer">
      <view class="cart-btn" @click="goToCart">
        <view class="badge">{{ cartCount }}</view>
        <image src="@/static/购物车.png" class="cart-icon" />
        <text>购物车</text>
      </view>
      <view class="button-group">
        <button class="add-cart" @click="showSku(true)">加入购物车</button>
        <button class="buy-now" @click="showSku(false)">立即购买</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { reqGoodsThumbImage, reqGoodsInfo } from '@/api/index';
import { reqAddHistory } from '@/api/user';
import { useCartStore } from '@/store/modules/cart';
import { useUserStore } from '@/store/index';
import { storeToRefs } from 'pinia';
import moment from 'moment';
// 设置中文语言
moment.locale('zh-cn');


const goodsId = ref('');
const thumbImages = ref([]);
const goodsInfo = ref({});
const cartStore = useCartStore();
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
const { totalCount: cartCount } = storeToRefs(cartStore);
const skuPopup = ref(null);
const buyNumber = ref(1);
const isSkuShowAddCart = ref(true);
const formatContent = ref('');

// 格式化上架时间的计算属性
const formattedAddTime = computed(() => {
  if (!goodsInfo.value.add_time) return '暂无';
  return moment(goodsInfo.value.add_time).format('YYYY-MM-DD HH:mm');
});

// 获取商品轮播图
const getGoodsThumbImage = async () => {
  const res = await reqGoodsThumbImage(goodsId.value);
  thumbImages.value = res.message;
};

// 获取商品信息
const getGoodsInfo = async () => {
  const res = await reqGoodsInfo(goodsId.value);
  goodsInfo.value = res.message;
  formatRichText(goodsInfo.value.content || '');
};

// 跳转到购物车
const goToCart = () => {
  uni.switchTab({
    url: '/pages/cart/cart',
  });
};

// 显示SKU弹窗
const showSku = (showAddCart = true) => {
  //判断是否登录
  if (!userInfo.value.username) {
    uni.navigateTo({
      url: '/pages/user_package/login/login'
    });
    return;
  }
  isSkuShowAddCart.value = showAddCart;
  skuPopup.value.open();
};

// 关闭SKU弹窗
const closeSkuPopup = () => {
  skuPopup.value.close();
};

// 数量变化处理
const onNumberChange = (value) => {
  buyNumber.value = value;
};

// 加入购物车
const handleAddCart = () => {
  //判断是否登录
  if (!userInfo.value.username) {
    uni.navigateTo({
      url: '/pages/user_package/login/login'
    });
    return;
  }
  const goods = {
    id: goodsId.value,
    number: buyNumber.value,
    sell_price: goodsInfo.value.sell_price,
    title: goodsInfo.value.title,
    thumb_path: goodsInfo.value.thumb_path || thumbImages.value[0]?.src,
    stock_quantity: goodsInfo.value.stock_quantity
  };


  if (cartStore.addToCart(goods)) {
    closeSkuPopup();
    uni.showToast({
      title: '已加入购物车',
      icon: 'success'
    });
  }
};

// 立即购买
const handleBuyNow = () => {
  const goods = {
    id: goodsId.value,
    number: buyNumber.value,
    sell_price: goodsInfo.value.sell_price,
    title: goodsInfo.value.title,
    thumb_path: goodsInfo.value.thumb_path || thumbImages.value[0]?.src,
    stock_quantity: goodsInfo.value.stock_quantity
  };

  if (cartStore.addToCart(goods)) {
    closeSkuPopup();
    // 跳转到购物车页面
    uni.switchTab({
      url: '/pages/cart/cart'
    });
  }
};

// 用户若登录了，则将商品加入历史记录
const addToHistory = async () => {
  if (userInfo.value.username) {
    await reqAddHistory(goodsId.value);
  }
};

const formatRichText = (html) => {
  if (!html) return '';
  // 处理图片宽度
  let newContent = html.replace(/<img/gi, '<img style="width:100%;height:auto;display:block;"');
  // 移除图片的width和height属性
  newContent = newContent.replace(/(width|height)=["'][^"']*["']/gi, '');
  formatContent.value = newContent;
};

// 页面加载时获取商品信息
onLoad((options) => {
  if (options.id) {
    goodsId.value = options.id;
    getGoodsThumbImage();
    getGoodsInfo();
    addToHistory();
  }
});
</script>

<style lang="scss" scoped>
$white: #fff;
@import '@/uni.scss';

.goodsdetail-container {
  background-color: $white;
  color: #666;
  background-color: #eee9e9;
  // #ifdef MP-WEIXIN
  padding-bottom: calc(120rpx + 38rpx); // 为底部操作栏和tabbar留出空间
  // #endif
  // #ifdef H5
  padding-bottom: 120rpx;
  // #endif

  .card {
    padding: px2rpx(8);
    margin: px2rpx(8);
    background: $white;
    border-radius: px2rpx(10);

    swiper {
      height: px2rpx(240);
    }

    swiper-item {
      display: flex;
      align-items: center;
      justify-content: center;

      image {
        width: px2rpx(245);
        height: 100%;
      }
    }

    .goodsName {
      font-size: px2rpx(16);
      font-weight: 500;
      color: #333;
    }

    .price {
      .sellPrice {
        margin-right: px2rpx(20);
        font-size: px2rpx(20);
        color: #fa865d;
      }

      .shopPrice {
        color: #666;
      }
    }

    .content {
      .rich-content {
        width: 100%;
      }
    }
  }

  .footer {
    position: fixed;
    left: 0;
    right: 0;
    // #ifdef MP-WEIXIN
    bottom: 28rpx; // 调整到tabbar上方
    // #endif
    // #ifdef H5
    bottom: 0;
    // #endif
    height: 100rpx;
    background: #fff;
    padding: 0 10rpx;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;

    &::after {
      content: '';
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      height: 38rpx;
      background-color: #fff; // 设置底部安全区的背景色，可以根据需要修改
      z-index: -1;
    }

    .cart-btn {
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 80rpx;
      margin-right: 10rpx;

      .badge {
        position: absolute;
        top: -4rpx;
        right: 0;
        min-width: 32rpx;
        height: 32rpx;
        background: #ff0000;
        color: #fff;
        font-size: 20rpx;
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1;
      }

      .cart-icon {
        width: 44rpx;
        height: 44rpx;
        margin-bottom: 4rpx;
      }

      text {
        font-size: 20rpx;
        color: #666;
        line-height: 1;
      }
    }

    .button-group {
      flex: 1;
      display: flex;
      align-items: center;
      padding: 0 10rpx;

      button {
        flex: 1;
        height: 80rpx;
        font-size: 28rpx;
        border: none;
        margin: 0;
        padding: 0;
        border-radius: 40rpx;

        &.add-cart {
          background: #ffa500;
          color: #fff;
          margin-right: 10rpx;
        }

        &.buy-now {
          background: #ff8c00;
          color: #fff;
        }
      }
    }
  }
}

.sku-popup {
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  position: relative;
  z-index: 100;

  &::after {
    content: '';
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    height: 200rpx; // 确保能完全遮住底部操作栏和安全区
    background-color: #fff;
    z-index: -1;
  }

  .sku-header {
    padding: 30rpx;
    display: flex;
    position: relative;
    border-bottom: 1rpx solid #f5f5f5;

    .goods-thumb {
      width: 160rpx;
      height: 160rpx;
      border-radius: 12rpx;
    }

    .sku-info {
      flex: 1;
      padding-left: 20rpx;

      .price {
        color: #ff6b00;
        font-size: 36rpx;
        font-weight: bold;
      }

      .stock,
      .selected {
        font-size: 24rpx;
        color: #666;
        margin-top: 10rpx;
      }
    }

    .close-btn {
      position: absolute;
      right: 20rpx;
      top: 20rpx;
      font-size: 48rpx;
      color: #999;
      padding: 10rpx;
    }
  }

  .sku-content {
    max-height: 600rpx;
    padding: 30rpx;

    .sku-item {
      margin-bottom: 30rpx;

      .item-title {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 20rpx;
        display: block;
      }
    }

    .other-info {
      .info-title {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 20rpx;
        display: block;
      }

      .info-item {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 10rpx;
      }
    }
  }

  .sku-footer {
    padding: 20rpx 30rpx;
    display: flex;
    gap: 20rpx;
    border-top: 1rpx solid #f5f5f5;
    margin-bottom: env(safe-area-inset-bottom); // 适配底部安全区

    button {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      border-radius: 40rpx;
      font-size: 28rpx;
      margin: 0;

      &.btn-cart {
        background: #ffa500;
        color: #fff;
      }

      &.btn-buy {
        background: #ff8c00;
        color: #fff;
      }
    }
  }
}
</style>
